package com.bjsxt.chapter1_singleton;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @ClassName Client2
 * @Description 测试反射和反序列化破坏懒汉式单例
 * @Author 黑马程序员
 * @Date 18:49 2024/6/18
 * @Version 1.0
 **/
public class Client2 {
    public static void main(String[] args) {
        // 正常调用
        /*SingletonDemo6 s1 = SingletonDemo6.getInstance();
        SingletonDemo6 s2 = SingletonDemo6.getInstance();
        System.out.println(s1 == s2);
        System.out.println(s1);
        System.out.println(s2);*/

        //reflect();

        serialize();
    }

    /**
     * 通过反射的方式直接调用私有构造器
     */
    public static void reflect(){
        try {
            SingletonDemo6 s = SingletonDemo6.getInstance();
            Class<SingletonDemo6> clazz = (Class<SingletonDemo6>) Class.forName("com.bjsxt.chapter1_singleton.SingletonDemo6");
            Constructor<SingletonDemo6> c = clazz.getDeclaredConstructor(null);
            c.setAccessible(true);
            SingletonDemo6 s1 = c.newInstance();
            SingletonDemo6 s2 = c.newInstance();
            System.out.println(s1);
            System.out.println(s2);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 通过反序列化的方式破坏单例
     */
    public static void serialize(){
        SingletonDemo6 s1 = SingletonDemo6.getInstance();
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        ObjectInputStream ois = null;
        FileInputStream fis = null;
        try {
            fos = new FileOutputStream("D:/a.txt");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(s1);

            fis = new FileInputStream("D:/a.txt");
            ois = new ObjectInputStream(fis);
            SingletonDemo6 s2 = (SingletonDemo6) ois.readObject();
            System.out.println(s1);
            System.out.println(s2);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ois != null){
                    ois.close();
                }
                if (fis != null){
                    fis.close();
                }
                if (oos != null){
                    oos.close();
                }
                if (fos != null){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
